package com.shushan.home;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.android.net.bean.NetRetBean;
import com.android.net.core.common.RequestType;
import com.android.net.helper.NetHelper;
import com.android.net.listener.common.CallbackCode;
import com.android.net.url.UrlParse;
import com.shushan.base.Constants;
import com.shushan.base.NavigationLoseActivity;
import com.shushan.home.bean.ExtractVipBean;
import com.shushan.home.bean.SectVipBean;
import com.shushan.network.UrlCommParse;
import com.shushan.network.UrlConst;
import com.shushan.network.listener.NetListCommListener;
import com.shushan.network.listener.NetSingleCommListener;
import com.shushan.pages.bean.WXPayBean;
import com.shushan.service.DialRTAService;
import com.shushan.shushanbao.BabyApplication;
import com.shushan.shushanbao.BuildConfig;
import com.shushan.shushanbao.R;
import com.shushan.shushanbao.wxapi.WXPayEntryActivity;
import com.shushan.ui.NestRadioGroup;
import com.shushan.util.PayUtils;
import com.shushan.util.SharedPreferencesUtils;
import com.shushan.util.ToolUtils;
import com.shushan.web.AdvertWebActivity;
import com.tencent.mm.opensdk.constants.Build;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import java.util.List;

/**
 * @ClassName: OpenSectVipActivity
 * @Desciption: 分练习开通VIP
 * @author: yichaohua
 * @date: 2018-10-31
 */
public class OpenSectVipActivity extends NavigationLoseActivity implements View.OnClickListener, NestRadioGroup.OnCheckedChangeListener {

    private static final String TAG = "OpenSectVipActivity";

    private NestRadioGroup radioGroup;
    private TextView typeText;
    private TextView moneyText;
    private TextView monthText;
    private TextView payText;
    private TextView spendText;
    private Button typeButton;

    private BabyApplication babyApplication = BabyApplication.getInstance();
    private IWXAPI api;
    private SectVipBean selectVipBean;
    private SectVipBean synchVipBean;
    private SectVipBean strangeVipBean;
    private SectVipBean oralVipBean;
    private SectVipBean speakVipBean;
    private SectVipBean wordVipBean;
    private SectVipBean hearVipBean;
    private int exerciseType;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.open_sect_vip_activity);

        setTitle("开通专项练习VIP");

        exerciseType = getIntent().getIntExtra("exerciseType",0);
        Log.i(TAG,"exerciseType=" + exerciseType);

        api = WXAPIFactory.createWXAPI(this, Constants.APP_ID);
        api.registerApp(Constants.APP_ID);

        initViwe();

        getData();
    }

    private void initViwe() {
        spendText = findViewById(R.id.sect_vip_spend_tv);
        radioGroup = findViewById(R.id.sect_vip_rg);
        radioGroup.setOnCheckedChangeListener(this);
        typeText = findViewById(R.id.open_sect_type_tv);
        moneyText = findViewById(R.id.open_sect_money_tv);
        monthText = findViewById(R.id.open_sect_month_tv);
        payText = findViewById(R.id.sect_vip_pay_tv);
        payText.setOnClickListener(this);
        typeButton = findViewById(R.id.open_sect_type_btn);
        typeButton.setOnClickListener(this);
    }

    private void getData() {
        showWaitDialog();

        UrlParse urlParse = new UrlCommParse(this, UrlConst.BASE_URL).appendRegion(UrlConst.GET_SECT_VIPS);

        NetHelper.create()
                .url(urlParse.toStringOnlyHeader())
                .param(urlParse.toStringOnlyParam())
                .request(RequestType.REQUEST_TYPE_POST, new NetListCommListener<SectVipBean>() {
                    @Override
                    protected void onCommon() {
                        dismissWaitDialog();
                    }

                    @Override
                    protected void onSuccess(List<SectVipBean> sectVipBeanList) {
                        if(!ToolUtils.isListEmpty(sectVipBeanList)){
                            synchVipBean = sectVipBeanList.get(0);
                            strangeVipBean = sectVipBeanList.get(1);
                            oralVipBean = sectVipBeanList.get(2);
                            speakVipBean = sectVipBeanList.get(3);
                            wordVipBean = sectVipBeanList.get(4);
                            hearVipBean = sectVipBeanList.get(5);

                            int resId;
                            switch (exerciseType){
                                case Constants.TYPE_SYNC_EXERCISE:
                                case Constants.TYPE_LEARN_BY_DO:
                                    selectVipBean = synchVipBean;
                                    resId = R.id.sect_vip_synch_rb;
                                    break;
                                case Constants.TYPE_STRANGE_WORDS_EXERCISE:
                                    selectVipBean = strangeVipBean;
                                    resId = R.id.sect_vip_strange_rb;
                                    break;
                                case Constants.TYPE_ORAL_CALCULATE_EXERCISE:
                                    selectVipBean = oralVipBean;
                                    resId = R.id.sect_vip_oral_rb;
                                    break;
                                case Constants.TYPE_SPEAKING_EXERCISE:
                                    selectVipBean = speakVipBean;
                                    resId = R.id.sect_vip_speak_rb;
                                    break;
                                case Constants.TYPE_ENGLISH_WORDS_EXERCISE:
                                    selectVipBean = wordVipBean;
                                    resId = R.id.sect_vip_word_rb;
                                    break;
                                case Constants.TYPE_HEARING_EXERCISE:
                                    selectVipBean = hearVipBean;
                                    resId = R.id.sect_vip_hear_rb;
                                    break;
                                default:
                                    selectVipBean = synchVipBean;
                                    resId = R.id.sect_vip_synch_rb;
                                    break;
                            }

                            radioGroup.check(resId);
                            if(selectVipBean != null){
                                typeText.setText("开通" + selectVipBean.type_name + "练习VIP");
                                moneyText.setText(selectVipBean.promotion_price + "元");
                                spendText.setText("￥" + selectVipBean.promotion_price + "元");
                                monthText.setText("购" + selectVipBean.vip_time + "个月");
                            }

                        }

                    }

                    @Override
                    protected void onError(CallbackCode errorCode, NetRetBean netRetBean) {
                        showNetError(netRetBean);
                    }
                });
    }

    @Override
    public void onCheckedChanged(NestRadioGroup group, int checkedId) {
        switch (checkedId){
            case R.id.sect_vip_synch_rb:
                selectVipBean = synchVipBean;
                break;
            case R.id.sect_vip_strange_rb:
                selectVipBean = strangeVipBean;
                break;
            case R.id.sect_vip_oral_rb:
                selectVipBean = oralVipBean;
                break;
            case R.id.sect_vip_speak_rb:
                selectVipBean = speakVipBean;
                break;
            case R.id.sect_vip_word_rb:
                selectVipBean = wordVipBean;
                break;
            case R.id.sect_vip_hear_rb:
                selectVipBean = hearVipBean;
                break;
            default:
                break;
        }

        if(selectVipBean != null){
            typeText.setText("开通" + selectVipBean.type_name + "练习VIP");
            moneyText.setText(selectVipBean.promotion_price + "元");
            monthText.setText("购" + selectVipBean.vip_time + "个月");
            spendText.setText("￥" + selectVipBean.promotion_price + "元");
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.sect_vip_pay_tv:
            case R.id.open_sect_type_btn:
                if("oppo".equals(BuildConfig.ENVIRONMENT)){
                    if(selectVipBean == null){
                        showToast("活动信息为空");
                        return;
                    }
                    PayUtils.orderOppoSectPay(this,selectVipBean.id,selectVipBean.vip_day_time,selectVipBean.promotion_price);
                } else if(getPackageName().equals(Constants.MASTER_PACKAGE_NAME)){
                    orderPay();
                }else {
                    PayUtils.sectVipHuawei(this,selectVipBean);
                }
                break;
            default:
                break;
        }
    }

    private void orderPay() {
        if(api.getWXAppSupportAPI() < Build.PAY_SUPPORTED_SDK_INT) {
            showToast("您未安装最新版本微信，不支持微信支付，请安装或升级微信版本");
            return;
        }

        if(selectVipBean == null){
            showToast("活动信息为空");
            return;
        }

        UrlParse urlParse = new UrlCommParse(this, UrlConst.BASE_URL).appendRegion(UrlConst.SECT_PAY_ORDER);
        urlParse.putValue("phone", SharedPreferencesUtils.getStringDate(Constants.LOGIN_MOBILE_SHAREPREFERS_KEY))
                .putValue("classification_vip_id",selectVipBean.id)
                .putValue("pay_type","app")
                .putValue("goods_name","开通专项练习VIP")
                .putValue("vip_time",selectVipBean.vip_day_time);

        if(BuildConfig.DEBUG){
            urlParse.putValue("money","0.01");
        }else {
            urlParse.putValue("money",selectVipBean.promotion_price);
        }

        showWaitDialog();
        NetHelper.create()
                .url(urlParse.toStringOnlyHeader())
                .param(urlParse.toStringOnlyParam())
                .request(RequestType.REQUEST_TYPE_POST, new NetSingleCommListener<WXPayBean>() {

                    @Override
                    protected void onCommon() {
                        super.onCommon();

                        dismissWaitDialog();
                    }

                    @Override
                    protected void onSuccess(WXPayBean wxPayBean) {
                        if(wxPayBean != null){
                            PayReq req = new PayReq();
                            req.appId			= wxPayBean.appid;
                            req.partnerId		= wxPayBean.partnerid;
                            req.prepayId		= wxPayBean.prepayid;
                            req.nonceStr		= wxPayBean.noncestr;
                            req.timeStamp		= wxPayBean.timestamp + "";
                            req.packageValue	= wxPayBean.packageName;
                            req.sign			= wxPayBean.sign;
                            req.extData			= "app data"; // optional

                            Log.i(TAG,"out_trade_no=" + wxPayBean.out_trade_no);
                            SharedPreferencesUtils.setStringDate(Constants.OUT_TRADE_NO_SHAREPREFERS_KEY,wxPayBean.out_trade_no);
                            WXPayEntryActivity.type = 2;

                            boolean isChildControl = SharedPreferencesUtils.getBooleanDate(Constants.IS_CHILD_CONTROL_SHAREPREFERS_KEY);
                            if(isChildControl){
                                setAllowBack(true);
                                Intent intent = new Intent(OpenSectVipActivity.this,DialRTAService.class);
                                intent.putExtra("rtaType",4);
                                intent.putExtra("allowPackName",Constants.ALLOW_WECHAT_PACK_NAME);
                                startService(intent);
                            }

                            // 在支付之前，如果应用没有注册到微信，应该先调用IWXMsg.registerApp将应用注册到微信
                            api.sendReq(req);
                        }else {
                            showToast("返回数据为空");
                        }

                    }

                    @Override
                    protected void onError(CallbackCode errorCode, NetRetBean netRetBean) {
                        showNetError(netRetBean);
                    }
                });
    }

}
